<?php

namespace api\modules\backend\controllers;

use yii\data\Pagination;
use common\commands\Common;
use api\modules\backend\models\Role;
use Yii;
use yii\filters\auth\QueryParamAuth;

/**
 * Role Controller API
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class RoleController extends ControllerBase
{
    public $modelClass = 'api\modules\v1\models\Role';
    public $defaultAvatar = 'uploads/images/avatar.png'; //默认头像路径
    private $notDeleted = 0; //未删除状态
    private $errorString; //错误信息

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [],
        ];
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }

    /**
     * 新增角色
     * @throws \yii\db\Exception
     */
    public function actionCreate()
    {
        $time = time();
        $roleModelClass = new Role();
        $post = Yii::$app->request->post();

        if (mb_strlen($post['password']) < 6 || mb_strlen($post['password']) > 20) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        if (!preg_match('/^(\w){4,20}$/', $post['password'])) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED1'));
        }

        $roleModelClass->load($post, '');
        $roleModelClass->setPassword(md5($post['password']));
        $roleModelClass->avatar = $this->defaultAvatar;
        $roleModelClass->create_time = $time;
        $roleModelClass->update_time = $time;

        $tr = Yii::$app->db->beginTransaction();
        try {

            if (!$roleModelClass->save()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();

        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, Yii::t('app', $e->getMessage())));
        }

        $this->success(array('role_id' => $roleModelClass->role_id));
    }

    /**
     * 角色列表
     */
    public function actionIndex()
    {
        $get = Yii::$app->request->get();

        $where = [
            'is_deleted' => $this->notDeleted
        ];
        $andFilterWhere = [];
        if (isset($get['role']) && is_numeric($get['role'])) $where['role'] = $get['role'];
        if (isset($get['mobile'])) $andFilterWhere = ['like', 'mobile', $get['mobile']];
        if (isset($get['active']) && is_numeric($get['active'])) $where['active'] = $get['active'];

        $roleModelClass = new Role();
        $roleFields = [
            'role_id',
            'role_name',
            'role',
            'mobile',
            'create_time',
            'update_time',
            'active'
        ];
        $roleQuery = $roleModelClass::find()->select($roleFields)->where($where)->andFilterWhere($andFilterWhere);

        $countQuery = clone $roleQuery;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $role = $roleQuery->offset($pages->offset)
            ->limit($pages->limit)
            ->orderBy(['update_time' => SORT_DESC, 'create_time' => SORT_DESC])
            ->asArray()
            ->all();

        $meta = array('totalCount' => (int)$pages->totalCount, 'perPage' => $pages->getPageSize(), 'pageCount' => $pages->getPageCount(), 'currentPage' => $pages->getPage() + 1);
        $result = array('item' => $role, '_meta' => $meta);

        $this->success($result);
    }

    /**
     * 角色详情
     */
    public function actionView()
    {
        $get = Yii::$app->request->get();

        $role_id = is_numeric($get['id']) ? $get['id'] : 0;

        $roleModelClass = new Role();
        $roleFields = [
            'role_id',
            'role_name',
            'role',
            'mobile',
            'account',
            'active'
        ];
        $role = $roleModelClass::find()->select($roleFields)
            ->where(['role_id' => $role_id, 'is_deleted' => $this->notDeleted])
            ->asArray()
            ->one();

        $data = array('role' => $role);
        $this->success($data);
    }

    /**
     * 更新角色
     * @throws \yii\db\Exception
     */
    public function actionUpdate()
    {
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();

        unset($post['account']);

        $role_id = is_numeric($get['id']) ? $get['id'] : 0;

        if (empty($role_id)) {
            $this->errorString = Yii::t('app', '{attribute} does not exist!', ['attribute' => Yii::t('app', 'role_id')]);
            $this->response(Common::getPackedResponse(DATABASE_FAILED, $this->errorString));
        }

        $roleModelClass = new Role();
        $role = $roleModelClass::findOne(['role_id' => $role_id, 'is_deleted' => $this->notDeleted]);

        if (empty($role)) {
            $this->errorString = Yii::t('app', '{attribute} does not exist!', ['attribute' => Yii::t('app', 'role')]);
            $this->response(Common::getPackedResponse(DATABASE_FAILED, $this->errorString));
        }

        $role->setAttributes($post);
        $role->update_time = time();

        if (isset($post['password']) && !empty($post['password'])) {
            if (mb_strlen($post['password']) < 6 || mb_strlen($post['password']) > 20) {
                $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED1'));
            }

            if (!preg_match('/^(\w){4,20}$/', $post['password'])) {
                $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED1'));
            }

            $role->setPassword(md5($post['password']));
        }

        if (!$role->validate()) {//验证数据
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $tr = Yii::$app->db->beginTransaction();//事务 如果失败 就会滚数据
        try {
            if (!$role->update()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();
        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $this->success(array('role_id' => $role_id));
    }

    /**
     * 删除角色
     * @throws \yii\db\Exception
     */
    public function actionDelete()
    {
        $user = Yii::$app->getUser();
        $get = Yii::$app->request->get();

        $role_id = is_numeric($get['id']) ? $get['id'] : 0;

        $roleModelClass = new Role();
        $role = $roleModelClass::findOne(['role_id' => $role_id, 'is_deleted' => $this->notDeleted]);

        if (empty($role)) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        if ((int)$user->id === (int)$role_id) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $role->is_deleted = 1;

        $tr = Yii::$app->db->beginTransaction();//事务 如果失败 就会滚数据
        try {
            if (!$role->update()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();
        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $this->success(array('role_id' => $role_id));
    }
}